<?php 

//任务管理公共函数

 /**
* 获取checkbox组合
*
* @param   array        $init_checkbox_array       组成多选框数组
* @param   string        $select_checkbox_array    已选数组
* @param   $checkbox_name     多选框名称
* @return  string
*/
function get_checkbox($init_checkbox_array, $select_checkbox_array, $checkbox_name) {
	
	$str = '';
	if ( empty($init_checkbox_array) || empty($checkbox_name) ) {
		return $str;
	}
	
	foreach ($init_checkbox_array AS $key => $value) {
		
		$is_select = false;
		if ( !empty($select_checkbox_array) ) {
			
			foreach ($select_checkbox_array AS $key1 => $value1) {
				if ( $value1 == $value['id'] ) {
					$is_select = true;
					$str .= '<input type="checkbox" name="'.$checkbox_name.'[]" value="'.$value['id'].'"  checked="checked"/>'.$value['name'].' &nbsp;&nbsp;';
				}
			}
		}
		
		if ( !$is_select ) {
			$str.='<input type="checkbox" name="'.$checkbox_name.'[]" value="'.$value['id'].'"  />'.$value['name'].' &nbsp;&nbsp;';
	
		}
	}
	
	return $str;

}


/**************************************
 * 往文件插入一条记录（注意记操作url）
 * @param $mDeleteFile   删除文件路径
 * @param $mEditFile   编辑文件路径
 * @param $mCdnFile   cdn文件路径
 * @param $type   类型
 * @return string
 **************************************/   
function  insertFile($mDeleteFile, $mEditFile, $url, $type) {
	
	
	$url = $url."\n";
	$file_name = '';
	if ($type == 'edit') {
		$file_name = $mEditFile;
	} elseif ($type == 'delete') {
		$file_name = $mDeleteFile;
	}
	
	if ( file_exists($file_name) ) {

		$contents = file_get_contents($file_name);
		
		if ( $type == 'edit'  ) {
			$d_contents = file_get_contents($mDeleteFile);
			$d_contents = str_replace($url, '', $d_contents);
			file_put_contents($mDeleteFile, $d_contents);
			
		} elseif ($type == 'delete') {
			$e_contents = file_get_contents($mEditFile);
			$e_contents = str_replace($url, '', $e_contents);
			file_put_contents($mEditFile, $e_contents);
		} 
		
		//判断url是否存在文件中
		if (substr_count($contents, $url) == 0) {
	
			file_put_contents($file_name, $url, FILE_APPEND);
		}
		
	}
	
}

/**************************************
 * 编辑删除url操作
 * @param $del_file_name   删除文件
 * @param $edit_file_name   编辑文件
 * @param $old_url   
 * @param $new_url  
 * @return string
 **************************************/   
function  editDocCollectUrl($del_file_name, $edit_file_name,  $old_url, $new_url ) {
	
	//删除文件处理
	if ( file_exists($del_file_name) ) {

		$contents = file_get_contents($del_file_name);
		$contents = str_replace($new_url."\n", '', $contents);

		//判断url是否存在文件中
		if (substr_count($contents, $old_url."\n") == 0) {
			$contents = $contents.$old_url."\n";
			
		}
		file_put_contents($del_file_name, $contents);
		
	}
	//更新文件处理
	if ( file_exists($edit_file_name) ) {
		$contents = file_get_contents($edit_file_name);
		$contents = str_replace($old_url."\n", '', $contents);
		file_put_contents($edit_file_name, $contents);
	}
	
}

/**
* 增加任务
* @param   array      $insert_array 增加数组
* @param   $IsFtp     是否为ftp上传
* @param   $isAuto    是否自动创建任务
* @param   $sId       站点ID
* @return  array
*/
function insertTask($insert_array = array(), $IsFtp, $isAuto = 0, $sId = 0) {
	
	if ( empty($insert_array) && $isAuto && $sId ) {
		
		$ftpStr = $IsFtp ? '_FTP' : '';
		$mName = $_SESSION['AName'].$ftpStr.'_'.date('Ymd').'_'.substr(time(), -5);
		$insert_array = array(	'mName' => $mName,
								'mCreatAid' => (int) $_SESSION['AID'],
								'mCreatTime' => $_SERVER['REQUEST_TIME'],
								'mIsFtp' => $IsFtp,
								'sId' => (int) $sId,
							);
	}
	
	$mId = $GLOBALS['db']->insert('task_manage', $insert_array);
	
	$update_array =  array();
	if ( !empty($mId) ) {
		
		//创建文件操作,以及修改
		$str = $IsFtp == 1 ?  'ftp' : 'cms';
	
// 		$filePath = IMG_ROOT."/pub_cms/{$str}/{$_POST['siteName']}/".date('Y')."/".date('m')."/{$_SESSION['AName']}/{$mId}";
		$filePath = IMG_ROOT."/pub_cms/{$str}/".date('Y')."/".date('m')."/{$_SESSION['AName']}/{$mId}";
		
		MakeDir1($filePath);
		
		$editFileName = $filePath.'/editUrls.txt';
		$delFileName = $filePath.'/delUrls.txt';
		$mCdnEditFile = $filePath.'/cdnEditUrls.txt';
		$mCdnDeleteFile = $filePath.'/cdnDelUrls.txt';
		$mMsgFile = $filePath."/pubMsg.txt";
		$mCdnMsgFile = $filePath."/cdnMsg.txt";	//pkjueying
	
		file_put_contents($editFileName, '');//新建修改增加文件
		file_put_contents($delFileName, '');//新建删除文件
		file_put_contents($mCdnEditFile, '');//新建修改增加文件
		file_put_contents($mCdnDeleteFile, '');//新建删除文件
		file_put_contents($mMsgFile, '');//发布过程中记录信息
		file_put_contents($mCdnMsgFile, '');//CDN推送记录信息	//pkjueying
		
		$update_array = array(	'mEditFile' => $editFileName,
								'mDeleteFile' => $delFileName,
								'mCdnEditFile' => $mCdnEditFile,
								'mCdnDeleteFile' => $mCdnDeleteFile,
								'mMsgFile' => $mMsgFile,
								'mCdnMsgFile' => $mCdnMsgFile,
							);
		$GLOBALS['db']->update('task_manage', $update_array, " mId = {$mId} ");
		
	}
	
	$update_array['mId'] = (int) $mId;
	unset($insert_array);
	return $update_array;
}


/**
* 检查是否有该网站的任务
* @param   int      $site_id 站点ID
* @return  array
*/
function  checkIsTask($site_id, $IsFtp) {
	
	$msg = '';
	$file_row =  getUserTaskFileInfo($site_id, $IsFtp);//获取任务相应的文件路径
	
	$location = "/wondershare/task_manage.php?action=editData&type=self&sId={$site_id}&IsFtp={$IsFtp}";
	if ( empty($file_row) ) {
		$file_row = insertTask(array(), $IsFtp, 1, $site_id);

	} elseif ( $file_row['mState'] != 0 ) {
		$msg = "你已经有该站点的任务，但未处理完，请赶快处理完任务吧！";
		$location = "/wondershare/task_manage.php?action=index&type=self&sId={$site_id}";
		
	} 
		
	if ( empty($msg) ) {
		return $file_row;
	} else {
		
		echo  '<script type="text/javascript"> 
				if (confirm("'.$msg.'") ) {
					window.location.href= "'.$location.'";
				} else {
				
					window.location.href="'.$_SERVER['HTTP_REFERER'].'";
				}
			</script>';
		exit;
	
	}
	
}

/**
* 返回队列信息 用于编辑（如果队列存在返回谁在操作处理，
* 如果队列不存在则插入一条记录到队列表中，并且进行编辑）
* @param   string      		 $url      编辑链接
* @param   int        	 	 $id       编辑ID
* @return  array
*/
function queueInfo($id = 0) {
	
	$url = $_SERVER['PHP_SELF'];

	$back_url = $_SERVER['HTTP_REFERER'];
	
	$str = '参数错误！';
	if ( !empty($url) && !empty($id) ) {

		$q_type = str_replace('.php', '', substr($url, strrpos($url, '/') + 1 ) );
		
		$data =  array( 'qFroeignId' => intval($id),
						'qType' => ucfirst($q_type),
						'qUserName' => $_SESSION['AName'],
						'qTime' => $_SERVER['REQUEST_TIME']
						);	
									
		$sql = "SELECT 
				qUserName, 
				qTime
				FROM task_queue
				WHERE qFroeignId = {$data['qFroeignId']} AND qType = '{$data['qType']}'  
				LIMIT 1";
		$row = $GLOBALS['db']->getOneRs($sql);
		
		if ( empty($row) ) {//表示队列库中木有可以编辑
			$GLOBALS['db']->insert('task_queue', $data);
			$str = '';
		} else {
			if ( $row['qUserName'] != $_SESSION['AName'] ) {
				$qTime = date('Y-m-d H:i:s', $row['qTime']);
				$str = "用户：{$row['qUserName']}\\n在时间：{$qTime} 编辑 \\n如果你想编辑请找他退出编辑吧！";
			} else {
				$str = '';
			}
		}
	}
	
	unset($row);
	if ( !empty($str) ) {
		echo '<script type="text/javascript">
				alert("'.$str.'");
				window.location.href = "'.$back_url.'";
			</script>';
	}
	
}

/**
* 删除队列记录
* @param   int      		$qid       队列主键
* @param   int        	 	 $id       编辑ID
* @return  array
*/
function queueDelete($str_qid = '', $id = 0, $type = '' , $url ='' , $t_id = '' , $d_id = '') {
	
	$str_qid = trim($str_qid);
	$id = intval($id);
	
	if ( !empty($url) ) {
		$url_array = explode('.php', $url);
		$url = $url_array[0].'.php';
		unset($url_array);
	} else {
		$url =  $_SERVER['PHP_SELF'] ;
	}
	
	$where_str = '';
	
	if ( !empty($str_qid) ) {//队列列表删除
		
		$where_str = " FIND_IN_SET(qId, '{$str_qid}') ";
		
	} elseif ( !empty($url) && !empty($id) ) {//编辑退出删除
	
		$q_type = ucfirst( str_replace('.php', '', substr($url, strrpos($url, '/') + 1 ) ) );
		$where_str = " qFroeignId = {$id} AND qType = '{$q_type}' AND qUserName = '{$_SESSION['AName']}' ";

	} elseif ( !empty($t_id) && !empty($d_id) ) {//编辑退出删除
	
		$q_type = 'Doc_'.$t_id;
		$where_str = " qFroeignId = {$d_id} AND qType = '{$q_type}' AND qUserName = '{$_SESSION['AName']}' ";
		
		
	} elseif($type == 'delAll') {//清除我的队列删除
		$where_str = ' 1=1 ';
	}

	$rows_affected = $GLOBALS['db']->delete('task_queue', $where_str);					
	$str = $rows_affected >= 1 ? '删除成功' : '删除失败'; 
	return $str;
	
}

/**
* 查看队列
* @param   string      		 $q_user_name      用户名称
* @return  array
*/
function queueSelect() {
	
	$where_str =  " WHERE qUserName = '{$_SESSION['AName']}' ";
	$queue_rows = array();
	$sql = "SELECT 
			qId,
			qFroeignId,
			qType,
			qTime,
			qUserName
			FROM task_queue
			{$where_str} ";
	$result = $GLOBALS['db']->query($sql);
	while ($row = $GLOBALS['db']->fetch_array($result, MYSQL_ASSOC)) {
		$row['qTime'] = date('Y-m-d H:i:s', $row['qTime']);
		$queue_rows[] = $row;
		
	}
	return $queue_rows; 

	
}

/**
* 查看队列数量
* @param   string      		 $q_user_name      用户名称
* @return  array
*/
function queueSum() {
	
	$where_str =  " WHERE qUserName = '{$_SESSION['AName']}' ";
	$sql = "SELECT 
			count(1) sum
			FROM task_queue
			{$where_str} ";
	$sum = $GLOBALS['db']->getOne($sql);
	return $sum; 

	
}

/**
* 查看是否有测试任务
* @param   string      		 $q_user_name      用户名称
* @return  array
*/
function testTaskManageSum() {
	
	$where_str =  " WHERE mTestAid = '{$_SESSION['AID']}' AND mState = 1 ";
	$sql = "SELECT 
			count(1) sum
			FROM task_manage
			{$where_str} ";
	$sum = $GLOBALS['db']->getOne($sql);
	return $sum; 

	
}

/**
* 查看是否有发布任务
* @param   string      		 $q_user_name      用户名称
* @return  array
*/
function pubTaskManageSum() {
	
	$where_str =  " WHERE mPubAid = '{$_SESSION['AID']}' AND mState = 3  ";
	$sql = "SELECT 
			count(1) sum
			FROM task_manage
			{$where_str} ";
	$sum = $GLOBALS['db']->getOne($sql);
	return $sum; 

	
}

/**
* 得到站点信息
* @param   INT      	$sId     站点id
* @param   INT      	$is_option     是否返回下拉框
* @return  array
*/
function getSiteInfo($sId = 0, $is_option = true) {
	
	$where_str = '';
	$sId = (INT) $sId;
	if ( !$is_option && !empty($sId) ) {
		$where_str = " sId = {$sId} AND  ";
	}
	
	$sql = "SELECT 
			sId,
			sDomainName
			FROM task_site
			WHERE {$where_str} sIsDelete = 0  ";
	if ($is_option) {
		$str = '';
		$result = $GLOBALS['db']->query($sql);
		while ($row = $GLOBALS['db']->fetch_array($result, MYSQL_ASSOC)) {
			if ($row['sId'] == $sId) {
					$str .= " <option value='{$row['sId']}' selected='selected'>{$row['sDomainName']}</option>";
			} else {
				$str .= " <option value='{$row['sId']}'>{$row['sDomainName']}</option>";
			}
		}
		return $str;
	} else {
		return $GLOBALS['db']->getAll($sql);
	}
}

/**
* 得到站点用户
* @param   INT      	$sId     站点id
* @param   INT      	$is_option     是否返回下拉框
* @return  array
*/
function getSiteUser($sId, $is_option = true) {
	
	$where_str = '';
	$sId = (INT) $sId;
	
	$sql = "SELECT 
			sMid
			FROM task_site
			WHERE sIsDelete = 0 AND sId = {$sId} ";
	$sql = "SELECT a.AName, a.AID 
			FROM Admin a, ({$sql}) t
			WHERE FIND_IN_SET(t.sMid, a.MPower) AND a.AName != ''
			ORDER BY  a.AName ASC";
	if ($is_option) {
		$str = '';
		$result = $GLOBALS['db']->query($sql);
		while ($row = $GLOBALS['db']->fetch_array($result, MYSQL_ASSOC)) {
			$str .= " <option value='{$row['AID']}'>{$row['AName']}</option>";
			
		}
		return $str;
	} else {
		return $GLOBALS['db']->getAll($sql);
	}
}

/**
* 获取任务相应的文件信息
* @param   INT      	$sId     站点id
* @param   INT      	$IsFtp   是否ftp上传
* @return  array
*/
function getUserTaskFileInfo($sId, $IsFtp = 0) {
	
	$sId = (int) $sId;
	$sql = "SELECT 
			mState,
			mEditFile,
			mCdnEditFile,
			mCdnDeleteFile,
			mDeleteFile
			FROM task_manage
			WHERE mCreatAid = '{$_SESSION['AID']}' AND sId = {$sId} AND mState != 4 AND mIsFtp = {$IsFtp} AND mIsDelete = 0";
	return $GLOBALS['db']->getOneRs($sql);
	
}

/**
* 根据站点对应服务器ID获取相应的服任务
* @param   int      $mId       任务ID
* @param   int      $mState    任务状态
* @return  array
*/
function updateTaskState($mId, $mState) {
	
	$mId = (int) $mId;
	if ( empty($mId) ) {
		return '任务ID不能为空！';
	}
	$data = array( 'mState' => (int) $mState );
	$rows_affected = $GLOBALS['db']->update('task_manage', $data, " mId = {$mId}");	
}

/**
 * 前台提示跳转
 * @param string $alert_title  弹出提示内容
 * @param string $location_url  跳转链接
 * @return string
 * */
 function mainAlert($alert_title, $location_url) {
 		
	echo "<script type='text/javascript'> 
			alert('{$alert_title}'); 
			window.location.href='{$location_url}'; 
		</script>";
		
 }
 
/**
* 获取站点信息
* @param   INT      	$sId     站点id
* @param   INT      	$IsFtp   是否ftp上传
* @return  array
*/
function getSiteDomain($sId) {
	
	$sId = (int) $sId;
	$sql = "SELECT 
			*
			FROM task_site
			WHERE  sId = {$sId}  AND sIsDelete = 0";
	return $GLOBALS['db']->getOneRs($sql);
	
}
 
?>